package com.guaoran.headFirst.observer;

import com.guaoran.headFirst.observer.interfaces.Observer;
import com.guaoran.headFirst.observer.interfaces.Subject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Observable;

/**
 * @author : 孤傲然
 * @Description :
 *  可观察者抽象类
 * @date :2018/4/27 13:49
 */
public abstract class AbstractSubject implements Subject{
    private List<Observer> observerList = Collections.synchronizedList(new ArrayList<Observer>());
    @Override
    public void addObserver(Observer observer) {
        if (observer == null) {
            throw new NullPointerException();
        }
        if (!observerList.contains(observer)) {
            observerList.add(observer);
        }

    }
    @Override
    public void removeObserver(Observer observer) {
        observerList.remove(observer);
    }
    @Override
    public void notifyObservers(String message) {
        observerList.stream().forEach(observer ->{
            if(observer instanceof Observer){
                observer.update(message);
            }
        });
    }

    @Override
    public void setMessage(String message) {
        notifyObservers(message);
    }
}
